package com.sailor.filter;

import com.google.common.base.Charsets;

import com.sailor.common.CommonResponse;
import com.sailor.config.ConfigCenter;
import com.sailor.util.JacksonUtil;
import org.springframework.http.MediaType;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 服务是否维护过滤器
 *
 * @author sailor
 * @date 2021-06-25
 **/
public class ServerMaintenanceFilter extends OncePerRequestFilter {
    private ConfigCenter configCenter;

    public ServerMaintenanceFilter(ConfigCenter configCenter) {
        this.configCenter = configCenter;
    }

    /**
     * Same contract as for {@code doFilter}, but guaranteed to be
     * just invoked once per request within a single request thread.
     * See {@link #shouldNotFilterAsyncDispatch()} for details.
     * <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
     * default ServletRequest and ServletResponse ones.
     *
     * @param request
     * @param response
     * @param filterChain
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if(configCenter.isServerDown()){
            CommonResponse error = CommonResponse.builder().message("服务正在维护中，请稍后访问").resultCode(1).build();
            response.setCharacterEncoding(Charsets.UTF_8.name());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            PrintWriter writer = response.getWriter();
            writer.write(JacksonUtil.obj2String(error));
            writer.flush();
            return;
        }
        filterChain.doFilter(request,response);
    }
}
